package com.swu.cx.alwayslearning.application

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.util.Log
import com.swu.cx.alwayslearning.classloader.HotfixUtil
import com.swu.cx.alwayslearning.classloader.ShareReflectUtil
import com.swu.cx.alwayslearning.util.DownLoadUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.io.File

class MyApp: Application() {

    companion object {
        @SuppressLint("StaticFieldLeak")
        private var _context: Context? = null
        val appContext: Context
            get() = _context!!
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        _context = base
        doHotFix(this)
    }

    private fun doHotFix(application: Application) {
        GlobalScope.launch(Dispatchers.IO) {
            val path = async {
                DownLoadUtil.downloadDex()
            }.await()
            val classLoader = application.classLoader
            HotfixUtil.installPatch(application, File(path))

            val pathListField = ShareReflectUtil.findField(classLoader, "pathList")
            val pathList = pathListField.get(application.classLoader)
            val dexElementsField = ShareReflectUtil.findField(pathList, "dexElements")
            (dexElementsField.get(pathList) as Array<Any>).forEach {
                Log.e("cx",it.toString())
            }
        }
    }

}